<template>
  <view>
    <!-- 导航栏 -->
    <view class="nav-bar">
      <view class="nav-left" @click="goBack">
        <text class="nav-back-icon">&lt;</text>
      </view>
      <view class="nav-title">注册</view>
      <view class="nav-right">
        <text class="nav-icon">⋯</text>
        <text class="nav-divider">|</text>
        <text class="nav-icon">⊙</text>
      </view>
    </view>
    
    <view class="container">
      <view class="blue-bg"></view>
      <view class="floating">
      <!-- 1. 商家信息（输入框） -->
      <view class="card info-card">
        <view class="row">
          <text class="label">负责人：</text>
          <input class="input" v-model="form.contactName" placeholder="请输入负责人姓名" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
        <view class="row">
          <text class="label">身份证号码：</text>
          <input class="input" v-model="form.idNumber" placeholder="请输入负责人的身份证号" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
        <view class="row">
          <text class="label">手机号：</text>
          <input class="input" v-model="form.phone" placeholder="请输入手机号" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
        <view class="row">
          <text class="label">验证码：</text>
          <view class="input-wrap code-wrap">
            <input class="inner-input" v-model="form.smsCode" placeholder="输入验证码" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
            <view class="code-link" :class="{disabled: countdown>0}" @tap="onGetCode">{{ countdown>0 ? countdown + 's' : '获取验证码' }}</view>
          </view>
        </view>
        <view class="row">
          <text class="label">店名：</text>
          <input class="input" v-model="form.storeName" placeholder="输入店名" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
        <view class="row">
          <text class="label label-wide">工商营业执照号码：</text>
          <input class="input" v-model="form.licenseNo" placeholder="请输入营业执照号" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
        <view class="row">
          <text class="label">经营区域：</text>
          <view class="select-input" @tap="showAddressSelector = true">
            <text :class="['select-text', { 'placeholder': !form.region }]">{{ form.region || '请选择区域' }}</text>
            <text class="select-arrow">﹀</text>
          </view>
        </view>
        <view class="row">
          <text class="label">地址：</text>
          <input class="input" v-model="form.address" placeholder="请输入详细地址" placeholder-style="color:#BFBFBF;font-size:26rpx;" />
        </view>
      </view>

      <!-- 2. 商家简介 -->
      <view class="card section-card">
        <view class="section-title">商家简介</view>
        <textarea class="textarea" v-model="form.intro" placeholder="请输入详细的商家介绍" placeholder-style="color:#BFBFBF;font-size:26rpx;" maxlength="500" />
      </view>

      <!-- 3. 身份证正反面图片（叠加上传） -->
      <view class="card section-card">
        <view class="section-title">身份证正反面照片</view>
        <view class="uploader">
          <view class="picker-row">
            <uni-file-picker fileMediatype="image" :limit="1" :image-styles="imageStyles" v-model="idFrontList" :auto-upload="false"></uni-file-picker>
            <uni-file-picker fileMediatype="image" :limit="1" :image-styles="imageStyles" v-model="idBackList" :auto-upload="false"></uni-file-picker>
          </view>
        </view>
      </view>

      <!-- 4. 营业执照（叠加上传） -->
      <view class="card section-card">
        <view class="section-title">营业执照</view>
        <view class="uploader">
          <uni-file-picker fileMediatype="image" :limit="2" :image-styles="imageStyles" v-model="licenseList" :auto-upload="false"></uni-file-picker>
          <view class="delete-row" v-if="licenseList.length">

          </view>
        </view>
      </view>

      <!-- 5. 门店照片（叠加上传） -->
      <view class="card section-card">
        <view class="section-title">门店照片</view>
        <view class="uploader">
          <uni-file-picker fileMediatype="image" :limit="2" :image-styles="imageStyles" v-model="storeList" :auto-upload="false"></uni-file-picker>
          <view class="delete-row" v-if="storeList.length">

          </view>
        </view>
      </view>

      <!-- 底部注册按钮 -->
      <view class="bottom-btn" @tap="onSave">注册</view>
      </view>
    </view>
    
    <!-- 地址选择器 -->
    <AddressSelector
      :visible="showAddressSelector"
      :defaultAddress="selectedAreaInfo"
      @cancel="handleAddressCancel"
      @confirm="handleAddressConfirm"
    />
  </view>
</template>

<script>
import AddressSelector from '@/components/AddressSelector.vue'

export default {
  components: {
    AddressSelector
  },
  data() {
    return {
      form: {
        contactName: '',
        idNumber: '',
        phone: '',
        smsCode: '',
        storeName: '',
        licenseNo: '',
        region: '',
        address: '',
        intro: '',
        longitude: '',
        latitude: ''
      },
      showAddressSelector: false,
      selectedAreaInfo: {},
      // 后端接口基础地址
      apiBaseUrl: 'http://localhost:9201',
      imageStyles: { width: 128, height: 128, border: { radius: 16 } },
      idFrontList: [],
      idBackList: [],
      licenseList: [],
      storeList: [],
      countdown: 0,
      timerId: null
    }
  },
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    // 验证手机号格式
    validatePhone(phone) {
      const phoneReg = /^1[3-9]\d{9}$/
      return phoneReg.test(phone)
    },
    
    // 开始倒计时
    startCountdown() {
      this.countdown = 60
      this.timerId && clearInterval(this.timerId)
      this.timerId = setInterval(() => {
        if (this.countdown <= 1) {
          clearInterval(this.timerId)
          this.timerId = null
          this.countdown = 0
        } else {
          this.countdown -= 1
        }
      }, 1000)
    },
    
    // 发送验证码
    async onGetCode() {
      if (this.countdown > 0) return
      
      // 验证手机号
      if (!this.form.phone) {
        uni.showToast({ title: '请输入手机号', icon: 'none' })
        return
      }
      
      if (!this.validatePhone(this.form.phone)) {
        uni.showToast({ title: '请输入正确的手机号格式', icon: 'none' })
        return
      }
      
      // 显示加载状态
      uni.showLoading({ title: '发送中...' })
      
      try {
        // 调用后端API发送验证码
        const response = await uni.request({
          url: `/api/system/sms/sendCode?phoneNumber=${this.form.phone}`,
          method: 'POST'
        })
        
        uni.hideLoading()
        
        // 处理响应
        if (response.statusCode === 200 && response.data) {
          const result = response.data
          
          if (result.code === 200) {
            // 发送成功
            uni.showToast({ 
              title: result.data || '验证码发送成功', 
              icon: 'success',
              duration: 2000
            })
            
            // 开始倒计时
            this.startCountdown()
            
            // 如果后端返回了验证码（开发环境可能会返回），可以在控制台显示
            if (result.msg && result.msg !== result.data) {
              console.log('验证码：', result.msg)
            }
          } else {
            // 业务错误
            uni.showToast({ 
              title: result.msg || '发送失败', 
              icon: 'none',
              duration: 2000
            })
          }
        } else {
          // HTTP错误
          uni.showToast({ 
            title: '网络请求失败', 
            icon: 'none',
            duration: 2000
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('发送验证码失败：', error)
        
        // 根据错误类型给出不同提示
        let errorMsg = '发送失败，请重试'
        if (error.errMsg) {
          if (error.errMsg.includes('timeout')) {
            errorMsg = '请求超时，请检查网络'
          } else if (error.errMsg.includes('fail')) {
            errorMsg = '网络连接失败'
          }
        }
        
        uni.showToast({ 
          title: errorMsg, 
          icon: 'none',
          duration: 2000
        })
      }
    },
    // 地址选择器取消
    handleAddressCancel() {
      this.showAddressSelector = false
    },
    // 地址选择器确认
    handleAddressConfirm(areaInfo) {
      this.showAddressSelector = false
      this.selectedAreaInfo = areaInfo
      
      console.log('选择的地址：', areaInfo)
      
      // 检查地址信息是否完整
      if (!areaInfo.province || !areaInfo.city || !areaInfo.area) {
        console.error('地址信息不完整：', areaInfo)
        uni.showToast({
          title: '请完整选择省市区',
          icon: 'none'
        })
        return
      }
      
      // 将选择的地址显示在表单中
      this.form.region = areaInfo.fullText
      
      // 组装最终用于查询的字符串：省市区 + 详细地址（纯字符串）
      const queryAddress = this.buildAddressQuery(areaInfo)
      console.log('将要调用接口的地址字符串：', queryAddress)
      
      // 调用接口获取经纬度
      this.getLocationByAddress(queryAddress)
    },
    
    // 构造查询字符串：省市区 + 详细地址，并去掉直辖市重复（如 北京市北京市）
    buildAddressQuery(areaInfo) {
      const province = (areaInfo.province || '').trim()
      const city = (areaInfo.city || '').trim()
      const area = (areaInfo.area || '').trim()
      const detail = (this.form.address || '').trim()
      
      const parts = []
      if (province) parts.push(province)
      // 直辖市等省市同名时去重
      if (city && city !== province) parts.push(city)
      if (area) parts.push(area)
      const base = parts.join('')
      return detail ? (base + detail) : base
    },
    
    // 根据地址获取经纬度
    async getLocationByAddress(address) {
      try {
        address = (address || '').trim()
        if (!address) {
          uni.showToast({ title: '地址为空，无法查询', icon: 'none' })
          return
        }
        console.log('开始获取地址位置信息，地址：', address)
        
        uni.showLoading({
          title: '获取位置信息中...'
        })
        
        // uni.request 在 await 下返回 [err, res]
        const requestUrl = (this.apiBaseUrl ? this.apiBaseUrl : '') + '/system/geo/addressToLocation'
        const token = uni.getStorageSync('token') || uni.getStorageSync('Authorization') || ''
        const [err, res] = await uni.request({
          url: requestUrl,
          method: 'GET',
          data: {
            // 直接传原始地址，uni.request 会正确处理编码
            address: address,
            _t: Date.now()
          },
          header: {
            'Content-Type': 'application/json',
            ...(token ? { 'Authorization': token.startsWith('Bearer') ? token : `Bearer ${token}` } : {})
          }
        })
        
        console.log('接口响应：', [err, res])
        
        uni.hideLoading()
        
        if (err) {
          console.error('请求错误：', err)
          uni.showToast({
            title: '请求失败，请检查网络',
            icon: 'none'
          })
          return
        }
        
        if (!res || !res.data) {
          console.error('接口响应异常：', res)
          uni.showToast({
            title: '接口响应异常',
            icon: 'none'
          })
          return
        }
        
        // 如果返回的是 HTML，基本可判断没有打到后端（多为前端静态页或未配置代理）
        const contentType = (res && res.header && (res.header['content-type'] || res.header['Content-Type'])) || ''
        if (typeof res.data === 'string' && res.data.includes('<!DOCTYPE html')) {
          console.error('疑似请求到了前端静态页面，请检查接口基地址或代理配置：', requestUrl)
          uni.showToast({
            title: '接口未指向后端，请配置基地址',
            icon: 'none'
          })
          return
        }

        const payload = res.data
        if (payload.code === 200) {
          const geoData = payload.data
          console.log('获取到的地理位置信息：', geoData)
          console.log('经度：', geoData.longitude)
          console.log('纬度：', geoData.latitude)
          console.log('详细地址：', geoData.address)
          console.log('省份：', geoData.province)
          console.log('城市：', geoData.city)
          console.log('区县：', geoData.district)
          console.log('格式化地址：', geoData.formattedAddress)
          
          // 保存经纬度
          this.form.longitude = geoData.longitude
          this.form.latitude = geoData.latitude
          
          uni.showToast({
            title: '位置信息获取成功',
            icon: 'success'
          })
        } else {
          console.error('接口返回错误：', payload)
          uni.showToast({
            title: payload.msg || '获取位置信息失败',
            icon: 'none'
          })
        }
      } catch (error) {
        uni.hideLoading()
        console.error('调用地理位置接口出错：', error)
        uni.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    },
    removeFrom(listKey, index) {
      this[listKey].splice(index, 1)
    },
    onSelect() {},
    onDelete() {},
    onSave() {
      uni.showToast({ title: '已保存', icon: 'success' })
    }
  },
  beforeDestroy() {
    this.timerId && clearInterval(this.timerId)
  }
}
</script>

<style scoped>
/* 导航栏样式 */
.nav-bar {
  height: 120rpx;
  background: #1f78ff;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 32rpx;
  z-index: 1000;
  box-sizing: border-box;
}

.nav-left {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.nav-left:active {
  transform: scale(0.95);
}

.nav-back-icon {
  color: #ffffff;
  font-size: 60rpx;
  font-weight: 200;
  line-height: 1;
}

.nav-title {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 500;
  padding-left: 40rpx;
  flex: 1;
  text-align: center;
}

.nav-right {
  display: flex;
  align-items: center;
  background: rgba(1, 1, 1, 0.2);
  border-radius: 50rpx;
  padding: 10rpx 20rpx;
  gap: 16rpx;
}

.nav-icon {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}

.nav-divider {
  color: #ffffff;
  font-size: 20rpx;
  opacity: 0.8;
}

.container { position: relative; min-height: 100vh; background-color: #f5f5f5;  /* 为固定导航栏留出空间 */ }
.blue-bg { width: 100%; height: 220rpx;background: #1f78ff; }
.floating { position: absolute; top: 20rpx; left: 50%; transform: translateX(-50%); width: 94%; }
.card { background-color: #ffffff; border-radius: 20rpx; box-shadow: 0 8rpx 32rpx rgba(0,0,0,0.1); padding:  32rpx; box-sizing: border-box; }
.info-card { margin-bottom: 24rpx; }
.row { display: flex; align-items: center; margin-bottom: 20rpx; }
.label { font-size: 24rpx; color: #333333; font-weight: 600; min-width: 220rpx; }
.label-wide { min-width: 220rpx; }
.input { flex: 1; height: 72rpx; line-height: 72rpx; padding: 0 24rpx; border: 2rpx solid #e9e9e9; border-radius: 36rpx; background-color: #ffffff; font-size: 26rpx; color: #333333; }
.input-wrap { flex: 1; height: 72rpx; border: 2rpx solid #e9e9e9; border-radius: 36rpx; background: #fff; display: flex; align-items: center; padding: 0 16rpx; box-sizing: border-box; }
.inner-input { flex: 1; height: 100%; line-height: 72rpx; padding: 0 8rpx; font-size: 26rpx; color: #333; }
.code-wrap { position: relative; }
.code-divider { width: 2rpx; height: 36rpx; background: #e6e6e6; margin: 0 12rpx; }
.code-link { color: #1677ff; font-size: 26rpx; white-space: nowrap; }
.code-link.disabled { color: #c0c4cc; }
.inline-group { flex: 1; display: flex; align-items: center; }
.divider { display:none; }
.code-btn { display:none; }
.input-with-code { position: relative; padding-right: 200rpx; }
.code-link { position: absolute; right: 40rpx; top: 50%; transform: translateY(-50%); color: #1677ff; font-size: 26rpx; padding-left: 16rpx; border-left: 5rpx solid #e5e5e5; }
.select-input { flex: 1; height: 72rpx; border: 2rpx solid #e9e9e9; border-radius: 36rpx; background: #fff; padding: 0 24rpx; box-sizing: border-box; position: relative; display: flex; align-items: center; }
.select-text { flex: 1; font-size: 26rpx; color: #333; }
.select-text.placeholder { color: #BFBFBF; }
.select-arrow { position: absolute; right: 24rpx; color: #9e9e9e; }
.section-card { margin-top: 24rpx; }
.section-title { font-size: 26rpx; color: #666666; margin-bottom: 20rpx; font-weight: 600; }
.textarea { width: 100%; min-height: 180rpx; padding: 20rpx 24rpx; border: 2rpx solid #e9e9e9; border-radius: 16rpx; background-color: #f9fafb; font-size: 26rpx; color: #333; box-sizing: border-box; }
.photos-row, .picker-row { display: flex; justify-content: flex-start; gap: 20rpx; }
.uploader { display: flex; flex-direction: column; align-items: flex-start; }
.delete-row { display: flex; gap: 12rpx; margin-top: 8rpx; }
.del { font-size: 24rpx; color: #666666; }
.bottom-btn { width: 70%; height: 88rpx; line-height: 88rpx; text-align: center; color: #ffffff; font-size: 30rpx; border-radius: 44rpx; background: linear-gradient(90deg, #3d7eff 0%, #1677ff 100%); box-shadow: 0 12rpx 32rpx rgba(22,119,255,.35); margin: 40rpx auto 20rpx; }
</style>